package sk.naive.talker.tcpadapter;

import sk.naive.talker.callback.Callback;
import sk.naive.talker.callback.CallbackException;

import java.rmi.RemoteException;
import java.util.*;

/**
 * Editor callback class.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.5 $ $Date: 2005/01/09 20:28:14 $
 */
public class Pager implements Callback {
	private int line = 0;
	private String[] pagedText;
	private boolean finished;
	private TCPUser user;

	public Pager(TCPUser user, String text) {
		text = user.sendReplace(text);
		this.user = user;
		List l = new LinkedList();
		String[] physicalLines = text.split(TCPUser.TCP_BR);
		for (int i = 0; i < physicalLines.length; i++) {
			l.addAll(AnsiUtils.splitLines(physicalLines[i], user.getCols()));
		}
		pagedText = (String[]) l.toArray(new String[l.size()]);
	}

	public void showPage() throws RemoteException {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < (user.getLines() - 1); i++) {
			sb.append(pagedText[line++]);
			sb.append(TCPUser.TCP_BR);
			if (line >= pagedText.length) {
				finished = true;
				break;
			}
		}
		if (!finished) {
			sb.append(TCPUser.messageFactory.getString("pager.prompt", user.getProperties()));
		}
		user.send(sb.toString());
	}

	public Callback process(String s)
		throws CallbackException
	{
		try {
			s = user.resolveResponse("pager.promptResolver", s);
			if (s.equals("end")) {
				finished = true;
				return null;
			}
			if (s.equals("") && s.equals("next")) {
				// no action required
			}
			showPage();
			if (finished) {
				return null;
			}
		} catch (RemoteException e) {
			throw new CallbackException(e);
		}
		return this;
	}

	public boolean isFinished() {
		return finished;
	}
}